package com.tinyspot.concrete.common.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @author Tinyspot
 * @date 2023-01-06 22:55
 */
public class CalculateUtil {

    /**
     * @param dividend 被除数
     * @param divisor 除数
     * @return
     */
    public static long longDivide(long dividend, long divisor) {
        if (divisor == 0) {
            return 0L;
        }
        BigDecimal dividendNum = new BigDecimal(Double.toString(dividend));
        BigDecimal divisorNum = new BigDecimal(Double.toString(divisor));
        return dividendNum.divide(divisorNum, 0, RoundingMode.HALF_UP).longValue();
    }

    public static double doubleDivide(long dividend, long divisor) {
        if (divisor == 0) {
            return 0L;
        }
        BigDecimal dividendNum = new BigDecimal(Double.toString(dividend));
        BigDecimal divisorNum = new BigDecimal(Double.toString(divisor));
        return dividendNum.divide(divisorNum, 2, RoundingMode.HALF_UP).doubleValue();
    }

    /**
     *
     * @param dividend 被除数
     * @param divisor 除数
     * @param scale 小数位
     * @param roundingMode 比如 BigDecimal.ROUND_HALF_UP 四舍五入
     * @return
     */
    public static BigDecimal divide(BigDecimal dividend, BigDecimal divisor, int scale, int roundingMode) {
        if (dividend == null || divisor == null) {
            return null;
        }
        if (divisor.compareTo(BigDecimal.ZERO) == 0) {
            return new BigDecimal("0");
        }
        return dividend.divide(divisor, scale, roundingMode);
    }

}
